<?php

namespace app\admin\controller;

use app\common\model\CouponLog;
use app\admin\model\User;
use app\common\controller\Backend;

/**
 * 优惠券信息
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{
    protected $searchFields = 'id,name';
    
    /**
     * Coupon模型对象
     * @var \app\common\model\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Coupon;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','name','start_money','discount_money','valid_time','type','status','create_time','update_time']);
                
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 发放优惠券
     */
    public function send(){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $coupon=$this->model::get(['id'=>$params['id']??0])?:[];
            if(!$coupon){
                $this->error('优惠券信息不存在');
            }
            if($coupon['status']!='normal'){
                $this->error('不可发放已下架优惠券');
            }

            if($params['type']=='all'){
                $ids=User::where(['status'=>'normal'])->column('id')?:[];
            }
            else{
                $id_arr=explode(',',$params['uid']);

                if(!$id_arr){
                    $this->error('请选择至少一个用户作为发放对象');
                }

                $ids=User::where(['status'=>'normal','id'=>$id_arr])->column('id')?:[];
                if(!$ids){
                    $this->error('请选择有效用户');
                }
            }

            $expire_time=$coupon['valid_time']*86400+time();

            $insert_data=[];
            foreach ($ids as $i){
                $insert_data[]=[
                    'user_id'=>$i,
                    'coupon_id'=>$params['id'],
                    'create_time'=>time(),
                    'expire_time'=>$expire_time
                ];
            }
            CouponLog::insertAll($insert_data);
            $this->success('成功');
        }

        $id=request()->param('id');
        if(!$id){
            $this->error('缺少优惠券id');
        }
        $this->view->assign("id", $id);
        return $this->view->fetch();
    }
}
